<?php
declare (strict_types = 1);

namespace app\model;

use think\helper\Str;
use think\Model;

/**
 * @mixin \think\Model
 */
class User extends Model
{
    protected $autoWriteTimestamp = true;

    public function getAvatarAttr($value)
    {
        return "/images/faces/avatar".($this->id%7).".png";
    }

    public function feed()//查询构造器
    {
        $user_ids=[];
        $users=$this->followings()->where('follower_id',$this->id)->select()->toArray();
        foreach($users as $v){
            array_push($user_ids,$v['id']);
        }
        array_push($user_ids,$this->id);

        return Topic::whereIn('user_id', $user_ids)->with('user')->order('id','desc');
        //with预加载（Eager Loading）每个话题关联的用户信息
        //避免N+1查询问题
    }

    public static function onBeforeDelete($user)
    {
       $user->topics()->delete();
    }//事件当删除用户，删除该用户的博文

    public static function onBeforeInsert($user)
    {
        $user->active_token =Str::random(10);
    }

    public function topics()
    {
        return $this->hasMany(Topic::class,'user_id','id');
        //一个作者有多篇文章
    }

    public function followers(){//关注我的粉丝
        //students classes classes_students   classes_id students_id 默认格式
        //user ,user  中间表明默认为user_user   user_id user_id
        //user_id- 中间表中指向当前模型的外键   follower_id- 中间表中指向关联模型的外键
        return $this->belongsToMany(User::class, Followers::class,'follower_id','user_id');
    }

    public function followings(){//我关注的人
        //students classes classes_students   classes_id students_id 默认格式
        //user  user  中间表明默认为user_user   user_id user_id

        return $this->belongsToMany(User::class, Followers::class,'user_id','follower_id');
    }

    //关注某人
    public function follower($user_id){
        $this->followings()->save($user_id);
    }
//取消关注某人
    public function unfollower($user_id)
    {
        $this->followings()->detach($user_id);

    }
//判断是否关注了某人
    public function isFollowing($user_id)
    {
        $users=$this->followings()->where('user_id', $user_id)->select();
        return !$users->isEmpty();
    }
//关注返回true,没有返回false

}
